const API_BASE_URL = 'http://localhost:8080/api';

interface LoginResponse {
  roles: { authority: string }[];
  message: string;
  status: string;
  username: string;
  token: string;
}

// 获取存储的 token
const getToken = (): string | null => {
  if (typeof window !== 'undefined') {
    return localStorage.getItem('auth-token');
  }
  return null;
};

// 设置 token 到存储
const setToken = (token: string): void => {
  if (typeof window !== 'undefined') {
    localStorage.setItem('auth-token', token);
  }
};

// 清除 token
const clearToken = (): void => {
  if (typeof window !== 'undefined') {
    localStorage.removeItem('auth-token');
  }
};

// 创建带有认证头的请求选项
const createAuthHeaders = (headers: HeadersInit = {}): HeadersInit => {
  const token = getToken();
  if (token) {
    return {
      ...headers,
      'Authorization': `Bearer ${token}`,
    };
  }
  return headers;
};

export const authApi = {
  login: async (username: string, password: string): Promise<LoginResponse> => {
    const requestBody = { username, password };
    console.log('登录请求参数:', requestBody);

    const response = await fetch(`${API_BASE_URL}/auth/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      credentials: 'include',
      body: JSON.stringify(requestBody),
    });

    const responseData = await response.json();
    console.log('登录响应数据:', responseData);

    if (!response.ok) {
      throw new Error(responseData.message || '登录失败');
    }

    // 存储 token
    if (responseData.token) {
      setToken(responseData.token);
    }

    return responseData;
  },

  logout: (): void => {
    clearToken();
  },

  // 通用请求方法
  request: async <T>(url: string, options: RequestInit = {}): Promise<T> => {
    const headers = createAuthHeaders({
      'Content-Type': 'application/json',
      ...options.headers,
    });

    const response = await fetch(`${API_BASE_URL}${url}`, {
      ...options,
      headers,
    });

    const data = await response.json();

    if (!response.ok) {
      throw new Error(data.message || '请求失败');
    }

    return data;
  },
}; 